package com.example.za.account.fragment;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.za.account.R;
import com.example.za.account.activity.InvestActivity;
import com.example.za.account.adapter.CommonAdapter;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.ExpenseDao;
import com.example.za.account.dao.IncomeDao;
import com.example.za.account.dao.InvestDao;
import com.example.za.account.model.Invest;
import com.example.za.account.utils.Constant;
import com.example.za.account.utils.DateUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class InvestFragment extends BaseFragment {

    @BindView(R.id.label_invest_remain)
    TextView labelInvestRemain;
    @BindView(R.id.label_invest_invest)
    TextView labelInvestInvest;
    @BindView(R.id.label_invest_idle)
    TextView labelInvestIdle;
    @BindView(R.id.btn_invest)
    Button btnInvest;
    @BindView(R.id.list_invest)
    ListView listInvest;
    Unbinder unbinder;

    private View rootView;
    private Context mContext;
    private float mIdle;
    private static final int REQUEST_INVEST = 0x123;
    private InvestDao mInvestDao;
    private CommonAdapter mCommonAdapter;
    private float mRemain;
    private float mSumInvested;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            mInvestDao = new InvestDao(mContext);
            getRemain();
            List<Invest> invest = mInvestDao.findInvest(DateUtils.getMonthStart(), DateUtils.getMonthEnd(),
                    AccountApplication.sUser.getmId());
            mSumInvested = 0;
            if (invest != null) {
                for (int i = 0; i < invest.size(); i++) {
                    mSumInvested += invest.get(i).getAmount();
                }
            }
            labelInvestInvest.setText(String.valueOf(mSumInvested));
            mIdle = mRemain - mSumInvested;
            if (mIdle < 0) {
                btnInvest.setEnabled(false);
            } else {
                btnInvest.setEnabled(true);
            }
            labelInvestIdle.setText(String.valueOf(mIdle));
            List<Invest> invests = mInvestDao.findAllInvest();
            mCommonAdapter = new CommonAdapter<Invest>(invests, R.layout.item_invest) {
                @Override
                public void bindView(ViewHolder holder, Invest obj) {
                    holder.setText(R.id.label_item_invest_type, obj.getType());
                    holder.setText(R.id.label_item_invest_amount, String.valueOf(obj.getAmount()));
                    holder.setText(R.id.label_item_invest_year, String.valueOf(obj.getYear()));
                    holder.setText(R.id.label_item_invest_rate, String.valueOf(obj.getRate()));
                    holder.setText(R.id.label_item_invest_earning, String.valueOf(obj.getEarning()));
                }
            };
            listInvest.setAdapter(mCommonAdapter);
        }

        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void getRemain() {
        Date start = DateUtils.getMonthStart();
        Date end = DateUtils.getMonthEnd();
        float incomes = new IncomeDao(mContext).getPeriodSumIncome(start, end, AccountApplication.sUser.getmId());
        float expenses = new ExpenseDao(mContext).getPeriodSumExpense(start, end, AccountApplication.sUser.getmId());
        mRemain = incomes - expenses;
        labelInvestRemain.setText(String.valueOf(mRemain));
    }

    @Subscribe
    public void refreshAccount(String message) {
        if (TextUtils.equals(message, "income_inserted") || TextUtils.equals(message, "expense_inserted")
                || TextUtils.equals(message, "income_updated") || TextUtils.equals(message, "expense_updated")
                || TextUtils.equals(message, "income_deleted") || TextUtils.equals(message, "expense_deleted")) {
            getRemain();
            List<Invest> invest = mInvestDao.findInvest(DateUtils.getMonthStart(), DateUtils.getMonthEnd(),
                    AccountApplication.sUser.getmId());
            mSumInvested = 0;
            if (invest != null) {
                for (int i = 0; i < invest.size(); i++) {
                    mSumInvested += invest.get(i).getAmount();
                }
            }
            labelInvestInvest.setText(String.valueOf(mSumInvested));
            mIdle = mRemain - mSumInvested;
            if (mIdle <= 0) {
                btnInvest.setEnabled(false);
            } else {
                btnInvest.setEnabled(true);
            }
            labelInvestIdle.setText(String.valueOf(mIdle));
            mCommonAdapter.setmData(mInvestDao.findAllInvest());

        }
    }

    @Override
    protected Fragment getSubFragment() {
        return this;
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_invest;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @OnClick(R.id.btn_invest)
    public void onViewClicked() {
        Intent intent = new Intent(mContext, InvestActivity.class);
        intent.putExtra(Constant.TYPE_INVEST, mIdle);
        startActivityForResult(intent, REQUEST_INVEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_INVEST && resultCode == Activity.RESULT_OK) {
            String stringExtra = data.getStringExtra(Constant.TYPE_INVEST);
            mCommonAdapter.setmData(mInvestDao.findAllInvest());
            mSumInvested += Float.parseFloat(stringExtra);
            mIdle = mRemain - mSumInvested;
            if (mIdle <= 0) {
                btnInvest.setEnabled(false);
            } else {
                btnInvest.setEnabled(true);
            }
            labelInvestInvest.setText(String.valueOf(mSumInvested));
            labelInvestIdle.setText(String.valueOf(mIdle));
        }
    }

}
